<?php

namespace app\api\controller;

use app\admin\model\App;
use app\admin\model\Appupdate;
use app\admin\service\Mail;
use app\admin\service\MailSendingTemplate;
use app\admin\service\Pay;
use app\admin\service\Upload;
use app\admin\service\QrCodeService;
use think\Db;
use think\facade\Request; 
use think\Validate;
use think\helper\Time;


class Api extends Common
{
    //获取app信息
    public function getApp()
    {   
                
        $data = [
            "rhtitle" => $this->app["rhtitle"],
            "rhappicon" => $this->app["rhappicon"],
            "rhver" => $this->app["versioncode"],
            "rhqq" => $this->app["rhqq"],
            "rhqun" => $this->app["rhqun"],
            "rhappmsg" => $this->app["appmsg"],
            "rhappview" => $this->app["appview"],
            "rhusernum" => db("user")->count()
        ];
        return $this->successjson("查询成功", $data);
    }

    //获取当前公告
    public function getNotice()
    {
        $appinfo = db("app")->find(); 
        $result = $appinfo['appmsg'];
        return $this->successjson("查询成功", $result);
    }

    //获取当前更新
    public function getUpdate()
    {
        $appupdate = new Appupdate();
        $result = $appupdate->getnewappupdate();
        return $this->successjson("查询成功", $result);
    }

    //获取更新历史记录
    public function getUpdatelist()
    {
        $result = db('appupdate')->order("time","desc")->select();
        return $this->successjson("查询成功", $result);
    }

    //增加访问量
    public function addview()
    {
        $appinfo = App::find();
        $appinfo['appview'] = $appinfo['appview'] + 1;
        $appinfo->save();
        return $this->successjson('ok');
    }

    //登录
    public function Login()
    {
        $data = input();
        $rule = [
            'username|用户名' => 'require|min:5|max:20|alphaNum',
            'password|密码' => 'require|min:5|max:20'
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$validate->check($data)) {
            return $this->errorjson($validate->getError());
        }
        $where = "username = '" . $data['username']. "'";
        $userinfo = db("user")->where($where)->find();
        if ($userinfo) {
            if ($userinfo["password"] == md5($data["password"])) {
                //是否禁用账号
                if ($userinfo["reasons"] == 1) {
                    return $this->errorjson($userinfo["reasons_ban"]);
                }
                //是否允许多设备登录同一账号
                // if ($this->app["is_equipment"] == 1) {
                //     if (!empty($userinfo["login_device"])) {
                //         if ($userinfo["login_device"] != $data["device"]) {
                //             return $this->errorjson("不允许新设备登录");
                //         }
                //     }
                // }
                //异地登录是否发送短信
                // if ($userinfo["ip"] != "") {
                //     if (!empty($ipaddress)) {
                //         $ipaddress = Common::getaddress($userinfo["ip"]);
                //         $ipaddress = json_decode($ipaddress, true);
                //     }
                //     $newipaddress = Common::getaddress(get_real_ip());
                //     $newipaddress = json_decode($newipaddress, true);
                //     if ($ipaddress["province"] . $ipaddress["city"] != $newipaddress["province"] . $newipaddress["city"]) {
                //         $temdata = [
                //             '{appname}' => $this->app["appname"],
                //             '{time}' => date("Y-m-d H:i:s", time()),
                //             '{username}' => $data["username"],
                //             '{nickname}' => $userinfo["nickname"],
                //             '{address}' => $newipaddress["province"] . $newipaddress["city"],
                //             '{ip}' => $newipaddress["ip"]
                //         ];
                //         Mail::sendEmail('', $userinfo["useremail"], "", MailSendingTemplate::newdevoice($temdata), 0);
                //     }
                // }
                if (!empty($newipaddress)) {
                    $newipaddress = Common::getaddress(get_real_ip());
                    $newipaddress = json_decode($newipaddress, true);
                }
                $usertoken = md5(getRandChar(15) . time());
                $result = [
                    "id" => $userinfo["id"],
                    "usertoken" => $usertoken,
                    "ip" => get_real_ip()
                ];
                db("user")->where("id", $userinfo["id"])->update($result);
                $result["username"] = $userinfo["username"];
                return $this->successjson("登录成功", $result);
            } else {
                return $this->errorjson("密码错误");
            }
        } else {
            return $this->errorjson("账号不存在");
        }
    }


    //注册
    public function Register()
    {
        $data = input();
        $rule = [
            'username|账号' => 'require|min:5|max:20|alphaNum',
            'password|密码' => 'require|min:5|max:20',
            'useremail|用户邮箱' => 'email',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        $username = db("user")->where("username", $data["username"])->count();
        if ($username != 0) {
            return $this->errorjson("账号已存在");
        }
        if (empty($data["useremail"])) {
            return $this->errorjson("请输入邮箱");
        }
        if(strpos($data["useremail"],'@qq.com') == false){
            return $this->errorjson("请输入QQ邮箱账号，只支持QQ邮箱");
        }
        $useremail = db("user")->where("useremail", $data["useremail"])->count();
        if ($useremail != 0) {
            return $this->errorjson("邮箱已存在");
        }
        $data["useremail"] == cookie("regemail");
        if (!input("?code")) {
            return $this->errorjson("请输入验证码");
        }
        $code = cookie("regcode");
        $regcodetime = cookie("regcodetime");
        if ($code == "") {
            return $this->errorjson("你还没发送验证码呢");
        }
        if (time() - $regcodetime > 300) {
            return $this->errorjson("验证码过期");
        }
        if (strtolower($code) != strtolower($data["code"])) {
            return $this->errorjson("验证码错误");
        }
        $qq=str_replace('@qq.com','',$data['useremail']);

        $urlPre='https://users.qzone.qq.com/fcg-bin/cgi_get_portrait.fcg?uins=';
        $datas=file_get_contents($urlPre.$qq);
        $datas=iconv("GB2312","UTF-8",$datas);
        $pattern = '/portraitCallBack\((.*)\)/is';
        preg_match($pattern,$datas,$result);
        $result=$result[1];
        $qqnickname = json_decode($result, true)["$qq"][6];
        if ($qqnickname) {
            $data["nickname"] = $qqnickname;
            $data["usertx"] = "http://q1.qlogo.cn/g?b=qq&nk=".$qq."&s=100&t=1547904810";
        }        
        $data["password"] = md5($data["password"]);
        $data["viptime"] = time() + ($this->app["zc_vip"] * 24 * 3600);
        $data["create_time"] = date("Y-m-d H:s:i", time());
        $data["ip"] = get_real_ip();
        $data["money"] = $this->app["zc_money"];
        $rs = db("user")->strict(false)->insert($data);
        if ($rs > 0) {
            return $this->successjson("注册成功");
        } else {
            return $this->errorjson("注册失败");
        }
    }

    //获取用户信息
    public function getUserInfo()
    {
        $data = input();
        $rule = [
            'username|用户名' => 'min:5|max:20|alphaNum',
            'id' => 'number',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if (!empty($data["username"]) && !empty($data["id"])) {
            return $this->errorjson("id和username必须传一个");
        }
        if (!empty($data["username"])) {
            $result = db("user")->where("username", $data["username"])->find();
        }
        if (!empty($data["id"])) {
            $result = db("user")->where("id", $data["id"])->find();
        }
        if ($result == null) {
            return $this->errorjson("用户不存在");
        }
        $res = [
            "id" => $result["id"],
            "username" => $result["username"],
            "usertx" => $result["usertx"],
            "userbg" => $result["userbg"],
            "nickname" => $result["nickname"],
            "money" => $result["money"],
            "viptime" => date("Y-m-d H:i:s", $result["viptime"]),
            "sex" => $result["sex"] == 0 ? "男" : "女",
            "useremail" => $result["useremail"],
            "signature" => $result["signature"],
            "invitecode" => $result["invitecode"],
            "reasons" => $result["reasons"] == 0 ? "正常" : "已封禁",
            "reasons_ban" => $result["reasons_ban"],
            "create_time" => $result["create_time"],
            "ip" => $result["ip"]
        ];
        //是否是会员
        if (time() < $result["viptime"]) {
            $res["vip"] = true;
        } else {
            $res["vip"] = false;
        }
        //签到天数
        $signinfo = db("sign")->where("userid", $result["id"])->find();
        $signlasttime = isset($signinfo["lasttime"]) ? $signinfo["lasttime"] : "";
        if ($signlasttime != "") {
            $res["signlasttime"] = date("Y-m-d H:i:s", $signlasttime);
        } else {
            $res["signlasttime"] = "";
        }
        list($starttime, $endtime) = Time::today();
        if ($signlasttime >= $starttime && $signlasttime <= $endtime) {
            $res["sign"] = true;
        } else {
            $res["sign"] = false;
        }
        $res["series_days"] = empty($signinfo["series_days"]) ? $signinfo["series_days"] : 0;
        $res["continuity_days"] = empty($signinfo["continuity_days"]) ? $signinfo["continuity_days"] : 0;
        //邀请总数
        $res["invitationcount"] = db("invitation")->where("userid", $result["id"])->count();
        //邀请人
        $inv = db("invitation")->where("newuserid", $result["id"])->find();
        if($inv){
            $invuser = db("user")->where("id", $inv["userid"])->find();
            $res["inviter"] = $invuser['nickname'];
        }else{
            $res["inviter"] = '暂无邀请人';
        }
        
        //软件数量
        $res["appnum"] = db("appdown")->where("appuserid", $result["id"])->count();
        //评论/评分数量
        $res["commentsnum"] = db("comments")->where("userid", $result["id"])->count();
        return $this->successjson("查询成功", $res);
    }

    //发送注册验证码
    public function sendRegcode()
    {
        $data = input();
        $regcodetime = cookie("regcodetime");
        if ($regcodetime != "" || !empty($regcodetime)) {
            if (time() - $regcodetime < 300) {
                return $this->errorjson("5分钟内只允许发一次");
            }
        }
        if (empty($data["useremail"])) {
            return $this->errorjson("请输入邮箱");
        }
        $useremail = db("user")->where("useremail", $data["useremail"])->find();
        if ($useremail) {
            return $this->errorjson("邮箱已被注册");
        }
        $code = getRandChar(6);
        cookie("regemail", $data["useremail"], 300);
        cookie("regcode", $code, 300);
        cookie("regcodetime", time(), 300);
        $temdata = [
            '{appname}' => $this->app["rhtitle"],
            '{useremail}' => $data["useremail"],
            '{code}' => $code,
        ];
        $res = Mail::sendEmail('', $data["useremail"], "", MailSendingTemplate::Register($temdata), 2);

        if ($res == 1) {
            return $this->successjson("发送成功");
        } else {
            return $this->errorjson($res);
        }
    }

    //用户签到
    public function UserSign()
    {
        $data = input();
        $rule = [
            'username|用户名' => 'min:5|max:20|alphaNum',
            'id' => 'number',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if (!empty($data["username"]) && !empty($data["id"])) {
            return $this->errorjson("id和username必须传一个");
        }
        if (!empty($data["username"])) {
            $result = db("user")->where("username", $data["username"])->find();
        }
        if (!empty($data["id"])) {
            $result = db("user")->where("id", $data["id"])->find();
        }
        if ($result == null) {
            return $this->errorjson("用户不存在");
        }
        $signinfo = db("sign")->where("userid", $result["id"])->find();
        $sign['money'] = $this->app["sign_money"];
        $sign['viptime'] = $this->app["sign_vip"];
        if ($signinfo) {
            list($startdaytime, $enddaytime) = Time::today();
            if ($signinfo["lasttime"] >= $startdaytime && $signinfo["lasttime"] <= $enddaytime) {
                return $this->errorjson("今天已经签到了");
            } else {
                list($yesterstartdaytime, $yesterenddaytime) = Time::yesterday();
                if ($signinfo["lasttime"] >= $yesterstartdaytime && $signinfo["lasttime"] <= $yesterenddaytime) {
                    $resdata = [
                        "continuity_days" => $signinfo["continuity_days"] + 1,
                    ];
                } else {
                    $resdata = [
                        "continuity_days" => 1,
                    ];
                }
                $resdata["lasttime"] = time();
                $resdata["series_days"] = $signinfo["continuity_days"] + 1;
                $rs = db("sign")->where("userid", $result["id"])->update($resdata);
                if ($rs > 0) {
                    if ($result["viptime"] >= time()) {
                        $userviptime = $result["viptime"];
                    } else {
                        $userviptime = time();
                    }
                    $updateuser = [
                        "money" => $result["money"] + $this->app["sign_money"],
                        "viptime" => $userviptime + $this->app["sign_vip"] * 24 * 3600,
                    ];
                    db("user")->where("id", $result["id"])->update($updateuser);
                    return $this->successjson("签到成功",$sign);
                } else {
                    return $this->errorjson("签到失败");
                }
            }
        } else {
            $adddata = [
                "continuity_days" => 1,
                "series_days" => 1,
                "lasttime" => time(),
                "userid" => $result["id"],
            ];
            $rs = db("sign")->strict(false)->insert($adddata);
            if ($rs > 0) {
                if ($result["viptime"] >= time()) {
                    $userviptime = $result["viptime"];
                } else {
                    $userviptime = time();
                }
                $updateuser = [
                    "money" => $result["money"] + $this->app["sign_money"],
                    "viptime" => $userviptime + $this->app["sign_vip"] * 24 * 3600,
                ];
                db("user")->where("id", $result["id"])->update($updateuser);
                return $this->successjson("签到成功",$sign);
            } else {
                return $this->errorjson("签到失败");
            }
        }
    }

    //发送找回密码验证码
    public function GetPasswordCode()
    {
        $data = input();
        if (!empty($data["username"])) {
            return $this->errorjson("请输入账号");
        }
        $username = db("user")->where("username", $data["username"])->find();
        if ($username) {
            if ($username["useremail"] == "") {
                return $this->errorjson("该账号未绑定任何邮箱");
            }
            // $passcodetime = cookie("passcodetime");
            // if ($passcodetime != "" || !empty($passcodetime)) {
            //     if (time() - $passcodetime < 300) {
            //         return $this->errorjson("5分钟内只允许发一次");
            //     }
            // }
            $code = getRandChar(6);
            cookie("passcode", $code, 300);
            cookie("passcodetime", time(), 300);
            $temdata = [
                '{appname}' => $this->app["rhtitle"],
                '{username}' => $username["username"],
                '{code}' => $code,
            ];
            $res = Mail::sendEmail('', $username["useremail"], "", MailSendingTemplate::findPassword($temdata), 2);
            if ($res == 1) {
                return $this->successjson("邮件发送成功");
            } else {
                return $this->errorjson($res);
            }
        } else {
            return $this->errorjson("该账号未被注册");
        }
    }

    //找回密码
    public function GetPassword()
    {
        $data = input();
        $rule = [
            'username|用户名' => 'require|min:5|max:20|alphaNum',
            'password|新密码' => 'require|min:5|max:20',
            'code|验证码' => 'require',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        $userinfo = db("user")->where("username", $data["username"])->find();
        if ($userinfo == null) {
            return $this->errorjson("账号不存在");
        }
        if (!input("?code")) {
            return $this->errorjson("请输入验证码");
        }
        $code = cookie("passcode");
        $passcodetime = cookie("passcodetime");
        if ($code == "") {
            return $this->errorjson("你还没发送验证码呢");
        }
        if (time() - $passcodetime > 300) {
            return $this->errorjson("验证码过期");
        }
        if (strtolower($code) != strtolower($data["code"])) {
            return $this->errorjson("验证码错误");
        }
        $update = [
            "password" => md5($data["password"]),
            "usertoken" => ''
        ];
        $rs = db('user')->where('id', $userinfo["id"])->update($update);
        return $this->successjson("修改成功");
    }

    //修改用户信息
    public function updateuserInfo()
    {
        $data = input();
        $rule = [
            'username|用户名' => 'min:5|max:20|alphaNum',
            'usertoken|用户token' => 'require',
            'id|用户id' => 'number',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if (!empty($data["username"]) && !empty($data["id"])) {
            return $this->errorjson("id和用户名必须传一个");
        }
        if (!empty($data["username"])) {
            $userinfo = db("user")->where("username", $data["username"])->find();
        }
        if (!empty($data["id"])) {
            $userinfo = db("user")->where("id", $data["id"])->find();
        }
        if ($userinfo == null) {
            return $this->errorjson("用户不存在");
        }
        if ($data["usertoken"] != $userinfo["usertoken"]) {
            return $this->errorjson("usertoken错误");
        }

        if (!empty($data["nickname"])) {
            $updatedata["nickname"] = $data["nickname"];
        }
        if(!empty($data["useremail"])){
            $updatedata["useremail"] = $data["useremail"];
            if ($userinfo["useremail"] != $data["useremail"]) {
                $emailuserinfo = db("user")->where("useremail", $data["useremail"])->find();
                if ($emailuserinfo != null) {
                    return $this->errorjson("邮箱已存在");
                }
            }
        }
        if (!empty($data["signature"])) {
            $updatedata["signature"] = $data["signature"];
        }
        if (!empty($data["sex"])) {
            if ($data["sex"] == "男") {
                $updatedata["sex"] = 0;
            } else {
                $updatedata["sex"] = 1;
            }
        }

        db("user")->where("id", $userinfo["id"])->update($updatedata);
        return $this->successjson("修改成功");
    }

    //头像上传
    public function UploadHead()
    {
        $data = input();
        $rule = [
            'username|用户名' => 'min:5|max:20|alphaNum',
            'usertoken|用户token' => 'require',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if (!empty($data["usertoken"])) {
            $userinfo = db("user")->where("usertoken", $data["usertoken"])->find();
        }
        if ($userinfo == null) {
            return $this->errorjson("用户不存在",$data["usertoken"]);
        }
        if ($data["username"] != $userinfo["username"]) {
            return $this->errorjson("用户验证失败");
        }
        $upload = new Upload();
        $result = $upload->upload('file', 1);
        $result = json_decode($result, true);
        if ($result["code"] == 200) {
            $usertx = $result["data"]["filePath"];
            db("user")->where("id", $userinfo["id"])->update(["usertx" => Request::domain().$usertx]);
            return $this->successjson('上传成功');
        } else {
            return $this->errorjson("上传失败");
        }
    }

    //背景上传
    public function UploadBg()
    {
        $data = input();
        $rule = [
            'username|用户名' => 'min:5|max:20|alphaNum',
            'usertoken|用户token' => 'require',
            'id|用户id' => 'number',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if (!empty($data["username"]) && !empty($data["id"])) {
            return $this->errorjson("id和用户名必须传一个");
        }
        if (!empty($data["username"])) {
            $userinfo = db("user")->where("username", $data["username"])->find();
        }
        if (!empty($data["id"])) {
            $userinfo = db("user")->where("id", $data["id"])->find();
        }
        if ($userinfo == null) {
            return $this->errorjson("用户不存在");
        }
        if ($data["usertoken"] != $userinfo["usertoken"]) {
            return $this->errorjson("usertoken错误");
        }
        $upload = new Upload();
        $result = $upload->upload('file', 1);
        $result = json_decode($result, true);
        if ($result["code"] == 200) {
            $userbg = $result["data"]["filePath"];
            db("user")->where("id", $userinfo["id"])->update(["userbg" => Request::domain().$userbg]);
            return $this->successjson('上传成功',["userbg" => Request::domain().$userbg]);
        } else {
            return $this->errorjson("上传失败");
        }
    }

    //图片上传
    public function UploadImg()
    {
        $upload = new Upload();
        $result = $upload->upload('file', 1);
        $result = json_decode($result, true);
        if ($result["code"] == 200) {
            $img = $result["data"]["filePath"];
            return $this->successjson('上传成功',["img" => Request::domain().$img]);
        } else {
            return $this->errorjson("上传失败");
        }
    }

    //积分排行榜
    public function UserList()
    {
        $data = input();
        $sortOrder = input('?sortOrder') ? input('sortOrder') : 'desc';
        if ($sortOrder != "desc" && $sortOrder != "asc") {
            return $this->errorjson("sortOrder参数错误");
        }
        $need_field = ['id', 'username', 'nickname', 'usertx', 'money'];
        $res = db('user')->order('money',$sortOrder)->field($need_field)->limit($this->limit)->select();
        foreach ($res as $key => $value) {
            $res[$key]["usertx"] = Request::domain() . $value["usertx"];
        }
        return $this->successjson("查询成功", $res);
    }

    //修改密码
    public function UpdatePassword()
    {
        $data = input();
        $rule = [
            'username|用户名' => 'min:5|max:20|alphaNum',
            'usertoken|用户token' => 'require',
            'oldpwd|老密码' => 'require',
            'newpwd|新密码' => 'require',
            'id' => 'number'
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if (!empty($data["username"]) && !empty($data["id"])) {
            return $this->errorjson("id和用户名必须传一个");
        }
        if (!empty($data["username"])) {
            $userinfo = db("user")->where("username", $data["username"])->find();
        }
        if (!empty($data["id"])) {
            $userinfo = db("user")->where("id", $data["id"])->find();
        }
        if ($userinfo == null) {
            return $this->errorjson("用户不存在");
        }
        if ($data["usertoken"] != $userinfo["usertoken"]) {
            return $this->errorjson("usertoken错误");
        }
        if ($userinfo['password'] != md5($data['oldpwd'])) {
            return $this->errorjson("旧密码错误");
        }
        if ($userinfo['password'] == md5($data['newpwd'])) {
            return $this->successjson("修改成功");
        }
        $update = [
            "password" => md5($data["newpwd"]),
            "usertoken" => ''
        ];
        db('user')->where("id", $userinfo["id"])->update($update);
        return $this->successjson("修改成功");
    }

    //生成邀请码
    public function Getinvitecode()
    {
        $data = input();
        $rule = [
            'username|用户名' => 'min:5|max:20|alphaNum',
            'usertoken|用户token' => 'require',
            'id' => 'number'
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if (!empty($data["username"]) && !empty($data["id"])) {
            return $this->errorjson("id和用户名必须传一个");
        }
        if (!empty($data["username"])) {
            $userinfo = db("user")->where("username", $data["username"])->find();
        }
        if (!empty($data["id"])) {
            $userinfo = db("user")->where("id", $data["id"])->find();
        }
        if ($userinfo == null) {
            return $this->errorjson("用户不存在");
        }
        if ($data["usertoken"] != $userinfo["usertoken"]) {
            return $this->errorjson("usertoken错误");
        }
        if ($userinfo['invitecode'] == "" || $userinfo['invitecode'] == null) {
            $invitecode = getRandChar(strlen($userinfo['username'])) . $userinfo["id"];
            db('user')->where('id', $userinfo['id'])->update(['invitecode' => $invitecode]);
            return $this->successjson("生成成功", $invitecode);
        } else {
            return $this->errorjson("已经生成过邀请码");
        }
    }

    //填写邀请码
    public function Invitation()
    {
        $data = input();
        $rule = [
            'username|用户名' => 'min:5|max:20|alphaNum',
            'usertoken|用户token' => 'require',
            'id' => 'number',
            'invitecode' => 'require'
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if (!empty($data["username"]) && !empty($data["id"])) {
            return $this->errorjson("id和用户名必须传一个");
        }
        if (!empty($data["username"])) {
            $userinfo = db("user")->where("username", $data["username"])->find();
        }
        if (!empty($data["id"])) {
            $userinfo = db("user")->where("id", $data["id"])->find();
        }
        if ($userinfo == null) {
            return $this->errorjson("用户不存在");
        }
        if ($data["usertoken"] != $userinfo["usertoken"]) {
            return $this->errorjson("usertoken错误");
        }
        $rs = db("invitation")->where("newuserid", $userinfo["id"])->find();
        if ($rs) {
            return $this->errorjson("已经填写过邀请码了");
        }
        $inviteuserinfo = db("user")->where("invitecode", $data["invitecode"])->find();
        if ($inviteuserinfo == null) {
            return $this->errorjson("邀请码不存在");
        }
        if ($inviteuserinfo["viptime"] >= time()) {
            $userviptime = $inviteuserinfo["viptime"];
        } else {
            $userviptime = time();
        }
        $updateinvitecode = [
            "money" => $inviteuserinfo["money"] + $this->app["invitation_money"],
            "viptime" => $userviptime + $this->app["invitation_vip"] * 24 * 3600,
        ];
        db("user")->where("id", $inviteuserinfo["id"])->update($updateinvitecode);
        $adddata = [
            "userid" => $inviteuserinfo["id"],
            "newuserid" => $userinfo["id"],
            "createtime" => date("Y-m-d H:i:s", time()),
        ];
        db("invitation")->insert($adddata);
        return $this->successjson("填写完成");
    }

    //邀请排行榜
    public function GetinviterList()
    {
        $sortOrder = input('?sortOrder') ? input('sortOrder') : 'desc';
        if ($sortOrder != "desc" && $sortOrder != "asc") {
            return $this->errorjson("sortOrder参数错误");
        }
        $result = db('invitation')
            ->alias("i")
            ->join('user u', "i.userid = u.id")
            ->group("i.userid")
            ->field("i.userid as id,count(i.id) as count,u.username,u.nickname,u.usertx")
            ->order("count", $sortOrder)
            ->limit($this->limit)
            ->select();
        foreach ($result as $key => $value) {
            $result[$key]["usertx"] = $value["usertx"];
        }
        return $this->successjson("查询成功", $result);
    }

    //使用卡密
    public function UserKm()
    {
        $data = input();
        $rule = [
            'username|用户名' => 'min:5|max:20|alphaNum',
            'id|用户id' => 'number',
            'km|卡密' => 'require'
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if (!empty($data["username"]) && !empty($data["id"])) {
            return $this->errorjson("id和用户名必须传一个");
        }
        if (!empty($data["username"])) {
            $userinfo = db("user")->where("username", $data["username"])->find();
        }
        if (!empty($data["id"])) {
            $userinfo = db("user")->where("id", $data["id"])->find();
        }
        if ($userinfo == null) {
            return $this->errorjson("用户不存在");
        }
        $kminfo = db("km")->where("km", $data["km"])->find();
        if ($kminfo == null) {
            return $this->errorjson("卡密不存在");
        }
        if ($kminfo["state"] == 1) {
            return $this->errorjson("卡密已被使用");
        }
        if ($userinfo["viptime"] >= time()) {
            $userviptime = $userinfo["viptime"];
        } else {
            $userviptime = time();
        }
        $updateuser = [
            "money" => $userinfo["money"] + $kminfo["money"],
            "viptime" => $userviptime + $kminfo["viptime"] * 24 * 3600,
        ];
        $km['money'] = $kminfo["money"];
        $km['viptime'] = $kminfo["viptime"];
        db("user")->where("id", $userinfo["id"])->update($updateuser);
        $updatekm = [
            "state" => 1,
            "username" => $userinfo["username"],
            "usetime" => date("Y-m-d H:i:s", time()),
        ];
        db("km")->where("id", $kminfo["id"])->update($updatekm);
        return $this->successjson("使用成功",$km);
    }

    //获取商品列表
    public function GetShopList()
    {
        $result = db("shop")
            ->select();
        return $this->successjson("查询成功", $result);
    }

    //获取商品信息
    public function GetShopInfo()
    {
        $data = input();
        $result = db("shop")->where("id", $data['id'])->find();
        if($result){
            return $this->successjson("查询成功", $result);
        }else{
            return $this->errorjson("商品不存在");
        }        
    }

    //购买商品
    public function BuyShop()
    {
        $data = input();
        $rule = [
            'usertoken' => 'require',
            'shopid|商品id' => 'require|number',
            'shoptype|支付方式' => 'require|number'
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if ($data["usertoken"]!='') {
            $userinfo = db("user")->where("usertoken", $data["usertoken"])->find();
        }
        if ($userinfo == null) {
            return $this->errorjson("用户不存在");
        }
        $shopinfo = db("shop")->where("id", $data["shopid"])->find();
        if ($shopinfo == null) {
            return $this->errorjson("商品不存在");
        }
        $app = db("app")->find();
        $order_no = getorderNumber("rh", $userinfo["id"]);
        //判断订单是否存在
        $shoptrade = db('order')->where('order_no', $order_no)->find();
        if ($shoptrade) {
            return $this->errorjson('订单已存在');
        }
        //判断支付方式类型
        if ($data["shoptype"] == 0) {
            
            try{
                $appId = $app['aliid'];//支付宝开发者平台的应用ID
                $PrivateKey = $app['aliprivatekey'];//支付宝私钥，由支付给的生成工具生成的目录下的私钥复制即可，一大串的
                $AliKey = $app['alikey'];//支付宝开放平台里给的支付宝公钥，就是拿工具生成的应用公钥到开放平台里换的支付宝公钥
                $notify_url =  $app['paynotify'];//返回地址
                $aop = new \AopClient();
                $order['order_no'] = $order_no;
                $order['shop_id'] = $shopinfo['id'];
                $order['price'] = $shopinfo['price'];
                $order['userid'] = $userinfo['id'];
                $order['createtime'] = date("Y-m-d H:i:s", time());
                $order['status'] = 0;
                $relus = db('order')->insert($order);
                
                $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do";
                $aop->appId = $appId;
                $aop->rsaPrivateKey = $PrivateKey;
                $aop->format = "json";
                $aop->postCharset = "UTF-8";
                $aop->signType = "RSA2";
                $aop->alipayrsaPublicKey = $AliKey;
                $request = new \AlipayTradeAppPayRequest();
                $arr['subject'] = $shopinfo['shopname'];
                $arr['out_trade_no'] = $data['out_trade_no'];
                $arr['timeout_express'] = '30m';
                $arr['total_amount'] = floatval($shopinfo['paymoney']);
                $arr['product_code'] = 'QUICK_MSECURITY_PAY';
                $json = json_encode($arr);
                $request->setNotifyUrl($notify_url.'&paytype=appali');
                $request->setBizContent($json);
                $result = $aop->sdkExecute($request);
                
            } catch(Exception $e) {
                Log::ERROR(json_encode($e));
            }
            
            echo json_encode($result);
        }   elseif ($data["shoptype"] == 1) {
            //获取易支付的支付方式
            $pay_type = input("?paytype") ? input("paytype") : "alipay";
            if ($pay_type != "alipay" && $pay_type != "qqpay" && $pay_type != "wxpay") {
                return $this->errorjson("易支付的支付方式错误");
            }
            $order['order_no'] = $order_no;
            $order['shop_id'] = $shopinfo['id'];
            $order['price'] = $shopinfo['price'];
            $order['userid'] = $userinfo['id'];
            $order['createtime'] = date("Y-m-d H:i:s", time());
            $order['status'] = 0;
            $relus = db('order')->insert($order);
            if($relus){
                // $o_info =  'pid='.$app['payid'].'&type='.$data['paytype'].'&out_trade_no='.$order['order_no']
                // .'&notify_url='.$app['paynotify'].'&return_url='.$app['paynotify'].'&name='.$shopinfo['name']
                // .'&money='.$order['price'];

                $o_info = 'money='.$order['price'].'&name='.$shopinfo['name'].'&notify_url='.$app['paynotify']
                .'&out_trade_no='.$order['order_no'].'&pid='.$app['payid'].'&return_url='.$app['payapi'].'&type='.$data['paytype'];
                $datas = $o_info .$app['paykey'];
                $sign = md5($datas);
                $data1 = $o_info.'&sign='.$sign.'&sign_type=MD5';
                echo "<script>location.href='".$app['payapi'].'submit.php?'.$data1."';</script>";
                return;
            }else{
                return $this->errorjson('订单入库失败');
            }
            // $sentData = $payment->createPaymentOrder(Pay::getPaymentById($data["shoptype"]), $orderdata, $result_type);
        } else {
            return $this->errorjson("服务器错误");
        }
    }


    //异步通知
    public function Paynotify(Request $request){
        $data = $request->param();
        $validate = Validate::make([
            'out_trade_no' => 'require',
            'trade_no' => 'require',
            'trade_status' => 'require',
        ]);
        if (!$validate->check($data)) {
            return $this->errorjson($validate->getError());
        }

        $shoptrade = db('order')->where('order_no', $data['out_trade_no'])->find();
        if (!$shoptrade) {
            return $this->errorjson('没有此订单');
        }
        $user = db('user')->where('id', $shoptrade['userid'])->find();
        if (!$user) {
            return $this->errorjson('没有此用户');
        }
        $shop = db('shop')->where('id', $shoptrade['shop_id'])->find();
        if (!$shop) {
            return $this->errorjson('没有此商品');
        }
        if(!empty($data['paytype'])){
            $types=$data['paytype'];
        }else{
            $types='';
        }
        if($types=='appali'){            
            if($shoptrade['status'] == 0 && $data['trade_status']=='TRADE_SUCCESS'){
                if ($user['viptime'] < time()) {
                    db('user')->where('username', $user['username'])->update(['viptime' => $user['viptime'] + $shop['vipnum'] * 24 * 3600]);
                    db('order')->where('order_no', $data['out_trade_no'])->update(['status' => 1, 'transaction_no' => $data['trade_no'],'paymenttime' => date("Y-m-d H:i:s", time())]);
                    return $this->returnJson("购买成功");
                } else {
                    db('user')->where('username', $user['username'])->update(['viptime' =>  time() + $shop['vipnum'] * 24 * 3600]);
                    db('order')->where('order_no', $data['out_trade_no'])->update(['status' => 1, 'transaction_no' => $data['trade_no'],'paymenttime' => date("Y-m-d H:i:s", time())]);
                    return $this->returnJson("购买成功");
                }
            }
        }else{
            if($shoptrade['status'] == 0 && $data['trade_status']=='TRADE_SUCCESS'){                
                if ($user['viptime'] < time()) {
                    db('user')->where('username', $user['username'])->update(['viptime' => $user['viptime'] + $shop['vipdate'] * 24 * 3600]);
                    db('order')->where('order_no', $data['out_trade_no'])->update(['status' => 1, 'transaction_no' => $data['trade_no'],'paymenttime' => date("Y-m-d H:i:s", time())]);
                    return $this->returnJson("购买成功");
                } else {
                    db('user')->where('username', $user['username'])->update(['viptime' =>  time() + $shop['vipnum'] * 24 * 3600]);
                    db('order')->where('order_no', $data['out_trade_no'])->update(['status' => 1, 'transaction_no' => $data['trade_no'],'paymenttime' => date("Y-m-d H:i:s", time())]);
                    return $this->returnJson("购买成功");
                }
            }
        }
    }
    //订单记录
    public function Getshoporder()
    {
        $data = input();
        $rule = [
            'usertoken|用户token' => 'require',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if ($data["usertoken"]!='') {
            $userinfo = db("user")->where("usertoken", $data["usertoken"])->find();
        }
        if ($userinfo == null) {
            return $this->errorjson("用户不存在");
        }
        $result = db('order')->alias('o')
            ->join("shop s", "s.id = o.shop_id")
            ->join("user u", "u.id = o.userid")
            ->where("userid", $userinfo["id"])
            ->field("o.*,u.username,s.price,s.name,s.detail")
            ->limit($this->limit)
            ->page($this->page)
            ->select();
        $resultnum = db('order')->alias('o')
            ->join("shop s", "s.id = o.shop_id")
            ->join("user u", "u.id = o.userid")
            ->where("userid", $userinfo["id"])
            ->count();
        return $this->successjson($resultnum, $result);
    }

    //查询订单的状态
    public function Getorderstatus()
    {
        $data = input();
        $rule = [
            'order_no|订单号' => 'require',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        $orderinfo = db("order")->where("order_no", $data["order_no"])->find();
        if ($orderinfo != null) {
            if ($orderinfo["status"] ==  1) {
                return $this->successjson(true);
            } else {
                return $this->successjson(false);
            }
        } else {
            return $this->errorjson("不存在此订单");
        }
    }

    //获取软件分类
    public function listSection()
    {
        $data = input();
        $result = db('appdownsort')            
            ->limit($this->limit)
            ->page($this->page)
            ->select();
        return $this->successjson("查询成功", $result);
    }


    //获取软件列表
    public function listApp()
    {
        $data = input();   
        //获取某分类全部软件
        if (!empty($data["appsortid"]) && empty($data["appmod"])){
            $where = "a.apppost = 1 and a.appsortid = {$data['appsortid']}";
            // echo '1';
        }
        //根据MOD筛选某分类下软件
        else if(!empty($data["appsortid"]) && !empty($data["appmod"])){
            $where = "a.apppost = 1 and a.appsortid = {$data['appsortid']} and a.appmod = {$data['appmod']}";
            // echo '2';
        }
        //不根据分类获取所有MOD条件的软件
        else if (!empty($data["appmod"]) && empty($data["appsortid"])) {
            $where = "a.apppost = 1 and a.appmod = {$data['appmod']}";
            // echo '3';
        }
        //获取所有置顶/精品软件
        else if(!empty($data["apptop"]) && empty($data["appsortid"])){
            $where = "a.apppost = 1 and  a.apptop = {$data['apptop']}";
        }
        //获取分类下置顶/精品条件软件
        else if(!empty($data["apptop"]) && !empty($data["appsortid"])){
            $where = "a.apppost = 1 and  a.appsortid = {$data['appsortid']} and a.apptop = {$data['apptop']}";
        }

        //获取用户的软件
        //根据用户名、状态获取软件信息
        if(!empty($data["username"]) && !empty($data["apppost"])){
            $userid  = db("user")->where("username", $data["username"])->find();
            $where = "a.apppost = {$data['apppost']} and a.appuserid = {$userid["id"]}";
        }
        //根据用户ID、状态获取软件信息
        if (!empty($data["id"]) && !empty($data["apppost"])) {
            $where = "a.apppost = {$data['apppost']} and a.appuserid = {$data["id"]}";
        } 

        //获取所有的未审核软件
        if(!empty($data['postapp'])){
            $where = "a.apppost = 0";
        }

        //模糊搜索
        if (!empty($data['appname'])) {
            $where = "a.apppost = 1 and a.appname like '%" . $data["appname"] . "%' or a.appmsg like '%" . $data["appname"] . "%'";
        }
        
        //标签ID获取
        if(!empty($data['tagid'])){
            $where = "CONCAT(',', a.apptagid, ',') LIKE CONCAT('%,', ".$data['tagid'].", ',%')";
        }
        
        $sortOrder = input("?sortOrder") ? $data["sortOrder"] : 'desc';
        if ($sortOrder != "desc" && $sortOrder != "asc") {
            return $this->errorjson("sortOrder参数错误");
        }
        $result = db('appdown')
        ->alias("a")
        ->join("appdownsort s", "s.id=a.appsortid")
        ->join("user u", "u.id=a.appuserid")
        ->where($where)
        ->field("a.*,s.sortname,u.username,u.nickname,u.usertx")
        ->order('apptime', $data['sortOrder'])
        ->limit($data['limit'])
        ->page($data['page'])
        ->select();
        $appcount = db('appdown')
        ->alias("a")
        ->join("appdownsort s", "s.id=a.appsortid")
        ->join("user u", "u.id=a.appuserid")
        ->where($where)
        ->count();
        $pagecount = ceil($appcount / $data['limit']);
        foreach ($result as $key => $value) {
            $result[$key]["usertx"] = $value["usertx"];
            //评论量
            $result[$key]["comment"] = db("comments")->where("appdownid", $value["id"])->count();
            $tagIdArr = explode(",",$value['apptagid']);
            foreach ($tagIdArr as $tagids => $tagid) {
                $result[$key]['apptag'][$tagids]['tagid'] = db('apptag')->where('id', $tagid)->value('id');
                $result[$key]['apptag'][$tagids]['tag'] = db('apptag')->where('id', $tagid)->value('tag');
            }

            //获取该软件评分人数
            $appstarnum = db("comments")->where("appdownid", $value["id"])->where("star","<",6)->count();
            //获取该软件评分数量的总分和
            $appallstar = db("comments")->where("appdownid", $value["id"])->where("star","<",6)->sum("star");
            //总分和除以评分人数得到最终评分
            if($appstarnum==0){
                $result[$key]['appstar'] = 5;
            }else{
                $result[$key]['appstar'] = ($appstarnum > 0) ? round($appallstar / $appstarnum, 2) : 0;
            }
        }
        return $this->successjson($pagecount, $result);
    }

    //获取最新/最热软件列表
    public function newhotApp()
    {
        $data = input();  
        $result = db('appdown')
        ->alias("a")
        ->join("appdownsort s", "s.id=a.appsortid")
        ->join("user u", "u.id=a.appuserid")
        ->where("a.apppost = 1")
        ->field("a.*,s.sortname,u.username,u.nickname,u.usertx")
        ->order($data['paixu'], 'desc')
        ->limit($data['limit'])
        ->page($data['page'])
        ->select();
        $appcount = db('appdown')
        ->alias("a")
        ->join("appdownsort s", "s.id=a.appsortid")
        ->join("user u", "u.id=a.appuserid")
        ->where("a.apppost = 1")
        ->count();


        $pagecount = ceil($appcount / $data['limit']);
        foreach ($result as $key => $value) {
            $result[$key]["usertx"] = $value["usertx"];
            //评论量
            $result[$key]["comment"] = db("comments")->where("appdownid", $value["id"])->count();
            $tagIdArr = explode(",",$value['apptagid']);
            foreach ($tagIdArr as $tagids => $tagid) {
                $result[$key]['apptag'][$tagids]['tagid'] = db('apptag')->where('id', $tagid)->value('id');
                $result[$key]['apptag'][$tagids]['tag'] = db('apptag')->where('id', $tagid)->value('tag');
            }

            //获取该软件评分人数
            $appstarnum = db("comments")->where("appdownid", $value["id"])->where("star","<",6)->count();
            //获取该软件评分数量的总分和
            $appallstar = db("comments")->where("appdownid", $value["id"])->where("star","<",6)->sum("star");
            //总分和除以评分人数得到最终评分
            if($appstarnum==0){
                $result[$key]['appstar'] = 5;
            }else{
                $result[$key]['appstar'] = ($appstarnum > 0) ? round($appallstar / $appstarnum, 2) : 0;
            }
        }
        return $this->successjson($pagecount, $result);
    }

    //获取软件标签列表
    public function gettags()
    {
        $data = input();  
        $result = db('apptag')
        ->order('id', 'desc')
        ->limit($data['limit'])
        ->page($data['page'])
        ->select();
        $tagcount = db('apptag')
        ->count();
        $pagecount = ceil($tagcount / $data['limit']);
        return $this->successjson($pagecount, $result);
    }

    //获取软件信息
    public function getAppinfo()
    {
        $data = input();
        $rule = [
            'id|软件id' => 'require|number',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }

        $appinfo = db("appdown")
            ->alias("a")
            ->join("user u", "u.id=a.appuserid")
            ->join("appdownsort p", "p.id=a.appsortid")
            ->field("a.id,a.appname,a.appicon,a.appsortid,a.apppage,a.appmsg,a.appmod,a.apptop,a.appbb,a.appuserid,a.apptagid,a.appdata,a.apphenfu,a.appsce,a.appdownnum,a.appisvip,a.apptime,u.username,u.nickname,u.usertx,p.sortname")
            ->where("a.id", $data["id"])
            ->find();
        if ($appinfo == null) {
            return $this->errorjson("软件不存在");
        }
        $appinfo["share"] = Request::domain().'/app/'.$data['id'];
        //评论量
        $appinfo["comment"] = db("comments")->where("appdownid", $data["id"])->count();
        $randomApps = db("appdown")
        ->alias("a")
        ->join("user u", "u.id=a.appuserid")
        ->join("appdownsort p", "p.id=a.appsortid")
        ->field("a.id,a.appname,a.appicon,a.appsortid,a.apppage,a.appmsg,a.appmod,a.apptop,a.appbb,a.appuserid,a.apptagid,a.appdata,a.apphenfu,a.appsce,a.appdownnum,a.appisvip,a.apptime,u.username,u.nickname,u.usertx,p.sortname")
        ->where("a.appsortid", $appinfo["appsortid"])
        ->limit(5)
        ->orderRaw("RAND()")
        ->select();
        $tagIdArr = explode(",",$appinfo['apptagid']);
        foreach ($tagIdArr as $tagids => $tagid) {
            $appinfo['apptag'][$tagids]['tagid'] = db('apptag')->where('id', $tagid)->value('id');
            $appinfo['apptag'][$tagids]['tag'] = db('apptag')->where('id', $tagid)->value('tag');
        }
        foreach ($randomApps as $key => $value) {
            //评论量
            $randomApps[$key]["comment"] = db("comments")->where("appdownid", $value["id"])->count();

            //获取该软件评分人数
            $appstarnum = db("comments")->where("appdownid", $value["id"])->where("star","<",6)->count();
            //获取该软件评分数量的总分和
            $appallstar = db("comments")->where("appdownid", $value["id"])->where("star","<",6)->sum("star");
            //总分和除以评分人数得到最终评分
            if($appstarnum==0){
                $randomApps[$key]['appstar'] = 5;
            }else{
                $randomApps[$key]['appstar'] = ($appstarnum > 0) ? round($appallstar / $appstarnum, 2) : 0;
            }
        }

        $appinfo['tuijian'] = $randomApps;
        //获取该软件评分人数
        $appstarnum = db("comments")->where("appdownid", $data["id"])->where("star","<",6)->count();
        //获取该软件评分数量的总分和
        $appallstar = db("comments")->where("appdownid", $data["id"])->where("star","<",6)->sum("star");
        //总分和除以评分人数得到最终评分
        if($appstarnum==0){
            $appinfo['star'] = 5;
        }else{
            $appinfo['star'] = ($appstarnum > 0) ? round($appallstar / $appstarnum, 2) : 0;
        }
        $appinfo['appstarnum']=$appstarnum;

        return $this->successjson("ok", $appinfo);
    }
    //下载软件
    public function downapp()
    {
        $data = input();
        $rule = [
            'id|软件id' => 'require|number',
            'username|用户名' => 'require',
            'token|用户token' => 'require'
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }

        $userinfo = db('user')->where('usertoken',$data['token'])->find();
        if($userinfo==null){
            return $this->errorjson("用户验证失败");
        }
        if($userinfo['username']!=$data['username']){
            return $this->errorjson("用户验证失败");
        }
        $appinfo = db('appdown')->where('id',$data['id'])->field('appdownurl,appisvip,appdownnum')->find();
        if($appinfo==null){
            return $this->errorjson("软件不存在");
        }
        if (time() < $userinfo["viptime"]) {
            $uservip = true;
        } else {
            $uservip = false;
        }
        if($appinfo['appisvip']==1&&$uservip==false){
            return $this->errorjson("您未开通会员");
        }else{
            $downnum = [
                'appdownnum' => $appinfo['appdownnum']+1,
            ];
            db("appdown")->where("id", $data["id"])->update($downnum);
            return $this->successjson("ok", $appinfo['appdownurl']);
        }
    }
    //上传软件
    public function upapp()
    {
        $upload = new Upload();
        $result = $upload->upload('file', 1);
        
        
        $result = json_decode($result, true);
        // echo json_encode($result);
        if ($result["code"] == 400) {
            return $this->errorjson("上传失败");
        }
        $apkParser = new \ApkParser\Parser('./'.$result['data']['filePath'], ['manifest_only' => false]);
        //获取软件图标索引
        $iconIndex = $apkParser->getManifest()->getApplication()->getIcon();
        //获取图标路径的数组
        $icons = $apkParser->getResources($iconIndex);
        //保存图标
        $files=file_put_contents('./uploads/icon/'.time().'.png', stream_get_contents($apkParser->getStream($icons[0])));
        //获取应用名称的索引
        $labelIndex = $apkParser->getManifest()->getApplication()->getLabel();
        //获取应用名称
        $appname = $apkParser->getResources($labelIndex)[0];
        
        
        $appsize = round($result['data']['size'] / 1048576 * 100) / 100 ;
        $appinfo = [
            //上传获取软件包名
            'apppage' => $apkParser->getManifest()->getPackageName(),
            //获取软件版本号
            'appbb' => $apkParser->getManifest()->getVersionName().' '.$apkParser->getManifest()->getVersionCode(),
            // //获取软件支持最低sdk的平台
            // 'appminsdk' => $apkParser->getManifest()->getMinSdk(),
            // //获取软件支持最低sdk的版本
            // 'appminsdks' => $apkParser->getManifest()->getMinSdkLevel(),
            // //获取软件Sdk的平台
            // 'appsdk' => $apkParser->getManifest()->getTargetSdk(),
            // //获取软件sdk的版本
            // 'appsdks' => $apkParser->getManifest()->getTargetSdkLevel(),
            //获取应用名称
            'appname' => $appname,
            //获取软件图标
            'appicon' => Request::domain().'/uploads/icon/'.time().'.png',
            //获取软件下载地址
            'appdownurl' => $result['data']['fullPath'],
            //获取软件大小
            'appsize' => $appsize
        ];     
        return $this->successjson("上传成功",$appinfo); 
    }

    //新增软件
    public function addapp()
    {
        $data = input();
        $rule = [
            'appusername|用户账号' => 'require',
            'usertoken' => 'require',
            'appname|软件名' => 'require',
            'appicon|软件图标' => 'require',
            'appsortid|分类id' => 'require|number',
            'apppage|软件包名' => 'require',
            'appmsg|软件介绍' => 'require',
            'appmod|是否MOD' => 'require|number',
            'appbb|软件版本' => 'require',
            'appdata|软件大小' => 'require|float',
            'apphenfu|软件横幅图' => 'require',
            'appsce|软件截图' => 'require',
            'appdownurl|软件下载地址' => 'require',
            'apptag|软件标签' => 'require'
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        $userinfo = db('user')->where('usertoken',$data['usertoken'])->find();
        if($userinfo==null){
            return $this->errorjson("用户验证失败");
        }
        if($userinfo['username']!=$data['appusername']){
            return $this->errorjson("用户验证失败");
        }
        $appinfo = db("appdown")->where("appname", $data["appname"])->where("appuserid", $userinfo["id"])->find();
        if ($appinfo) {
            return $this->errorjson("你已经发布过相同软件");
        }
        $sortinfo = db("appdownsort")->where("id", $data["appsortid"])->find();
        if ($sortinfo == null) {
            return $this->errorjson("分类不存在");
        }

        $tagArr = array_unique(explode(";",$data['apptag']));
		$tagIds = [];
		foreach ($tagArr as $tag) {
		    $id = db('apptag')->where('tag', $tag)->value('id');
		    if ($id) {
		        $tagIds[] = $id;
		    } else {
		        $tagIds[] = db('apptag')->insertGetId(['tag' => $tag]);
		    }
		}	
        $adddata = [
            "appuserid" => $userinfo["id"],
            "appname" => $data["appname"],
            "appsortid" => $data["appsortid"],
            "apppage" => $data["apppage"],
            "appmsg" => $data["appmsg"],
            "apptime" => date("Y-m-d H:i:s", time()),
            "appmod" => $data["appmod"],
            "appdata" => $data["appdata"],
            "apphenfu" => $data["apphenfu"],
            "appsce" => $data["appsce"],
            "appdownurl" => $data["appdownurl"],
            "apptagid" => implode(',', array_map('strval', $tagIds)),
            "apppost" => 0,
            "appicon"=> $data["appicon"],
            "appbb"=> $data["appbb"],
        ];
        db("appdown")->insert($adddata);
        return $this->successjson("ok");
    }

    //删除软件
    public function deleteApp()
    {
        $data = input();
        $rule = [
            'userid|用户id' => 'number',
            'id|软件ID' => 'require|number',
            'usertoken' => 'require',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if (!empty($data["id"])) {
            $userinfo = db("user")->where("id", $data["userid"])->find();
        }
        if ($userinfo == null) {
            return $this->errorjson("用户不存在");
        }
        if ($userinfo["usertoken"] != $data["usertoken"]) {
            return $this->errorjson("usertoken错误");
        }
        $appinfo = db("appdown")->where("id", $data["id"])->find();
        if ($appinfo == null) {
            return $this->errorjson("软件不存在");
        }

        if ($data['userid']=='1'||$data['userid']==$appinfo['appuserid']) {
            db("appdown")->where("id", $data["id"])->delete();
            return $this->successjson("删除成功");
        }else {
            return $this->errorjson("无权限");
        }
    }

    //编辑软件
    public function editApp()
    {
        $data = input();
        $rule = [
            'appuserid|用户id' => 'number',
            'usertoken' => 'require',
            'appname|软件名' => 'require',
            'appicon|软件图标' => 'require',
            'appsortid|分类id' => 'require|number',
            'apppage|软件包名' => 'require',
            'appmsg|软件介绍' => 'require',
            'appmod|是否MOD' => 'require|number',
            'appbb|软件版本' => 'require',
            'appdata|软件大小' => 'require|float',
            'apphenfu|软件横幅图' => 'require',
            'appsce|软件截图' => 'require',
            'appdownurl|软件下载地址' => 'require',
            'apptag|软件标签' => 'require',
            'id|软件id' => 'require',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if (!empty($data["id"])) {
            $userinfo = db("user")->where("id", $data["appuserid"])->find();
        }
        if ($userinfo == null) {
            return $this->errorjson("用户不存在");
        }
        if ($userinfo["usertoken"] != $data["usertoken"]) {
            return $this->errorjson("usertoken错误");
        }
        $appinfo = db("appdown")->where("id", $data["id"])->find();
        if ($appinfo == null) {
            return $this->errorjson("软件不存在");
        }
        
        if($data['appname']!=''){
            $adddata["appname"] = $data["appname"];
        }
        if($data['appsortid']==''){
            $adddata["appsortid"] = $data["appsortid"];
        }
        if($data['apppage']==''){
            $adddata["apppage"] = $data["apppage"];
        }
        if($data['appmsg']==''){
            $adddata["appmsg"] = $data["appmsg"];
        }
        if($data['appbb']==''){
            $adddata["appbb"] = $data["appbb"];
        }
        if($data['appmod']==''){
            $adddata["appmod"] = $data["appmod"];
        }
        if($data['appdata']==''){
            $adddata["appdata"] = $data["appdata"];
        }
        if($data['apphenfu']==''){
            $adddata["apphenfu"] = $data["apphenfu"];
        }
        if($data['appsce']==''){
            $adddata["appsce"] = $data["appsce"];
        }
        if($data['appdownurl']==''){
            $adddata["appdownurl"] = $data["appdownurl"];
        }
        if($data['apptag']==''){
            $tagArr = array_unique(explode(";",$data['apptag']));
            $tagIds = [];
            foreach ($tagArr as $tag) {
                $id = db('apptag')->where('tag', $tag)->value('id');
                if ($id) {
                    $tagIds[] = $id;
                } else {
                    $tagIds[] = db('apptag')->insertGetId(['tag' => $tag]);
                }
            }
            $adddata["apptagid"] = implode(',', array_map('strval', $tagIds));
        }
        if($data['appicon']==''){
            $adddata["appicon"] = $data["appicon"];
        }
        $adddata = [
            "appuserid" => $data["appuserid"],
            "apptime" => date("Y-m-d H:i:s", time()),
            "apppost" => 0,
        ];
        if ($data["appuserid"]=='1'||$data['appuserid']==$appinfo['appuserid']) {
            db("appdown")->where("id", $data["id"])->update($adddata);
            return $this->successjson("修改成功，软件已进入审核");
        }else{
            return $this->errorjson("不能修改他人软件");
        }        
    }


    //审核软件
    public function reviewArticle()
    {
        $data = input();
        $rule = [
            'userid|用户id' => 'number',
            'usertoken' => 'require',
            'appid|软件id' => 'require'
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if ($data["userid"]!='') {
            $userinfo = db("user")->where("id", $data["userid"])->find();
        }
        if ($userinfo == null) {
            return $this->errorjson("用户不存在");
        }
        if ($userinfo["usertoken"] != $data["usertoken"]) {
            return $this->errorjson("usertoken错误");
        }
        $appinfo = db("appdown")->where("id", $data["appid"])->find();
        if ($appinfo == null) {
            return $this->errorjson("软件不存在");
        }
        if ($userinfo['id']==1) {
            db("appdown")->where("id", $data["appid"])->update(["apppost" => 1]);
            return $this->successjson("审核通过");
        } else {
            return $this->errorjson("你不是管理员，无法审核");
        }
    }

    //发表评论/评分
    public function comment()
    {
        $data = input();
        $rule = [
            'username|用户名' => 'require',
            'usertoken' => 'require',
            'appid|软件id' => 'require|number',
            'content|评论内容' => 'require',
            'parentid|评论的id' => 'number',
            'star' => 'float'
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if (!empty($data['usertoken'])) {
            $userinfo = db("user")->where("usertoken", $data["usertoken"])->find();
        }
        if ($userinfo == null) {
            return $this->errorjson("用户未登录");
        }
        if ($userinfo["username"] != $data["username"]) {
            return $this->errorjson("用户TOKEN错误");
        }
        $appinfo = db("appdown")->where("id", $data["appid"])->find();
        if ($appinfo == null) {
            return $this->errorjson("帖子不存在");
        }
        $addcommentdata = [
            "parentid" => $data["parentid"],
            "star" => $data["star"],         
            "content" => $data["content"],
            "userid" => $userinfo["id"],
            "appdownid" => $data["appid"],
            "time" => date("Y-m-d H:i:s", time()),
        ];
        $isstar = db("comments")->where("userid", $userinfo["id"])->where("star",'<6')->find();
        $iscomment = db("comments")->where("userid", $userinfo["id"])->where("content",$data['content'])->find();
        if($isstar){
            return $this->errorjson("你已参与评分");
        }else if($iscomment){
            return $this->errorjson("不可发布重复评论");
        }else{
            db("comments")->insertGetId($addcommentdata);
            return $this->successjson("评论成功");
        }
        
    }

    //删除评论
    public function deleteComment()
    {
        $data = input();
        $rule = [
            'userid|用户id' => 'number',
            'usertoken' => 'require',
            'id|评论id' => 'require|number',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if ($data["userid"]!='') {
            $userinfo = db("user")->where("id", $data["userid"])->find();
        }
        if ($userinfo == null) {
            return $this->errorjson("用户不存在");
        }
        if ($userinfo["usertoken"] != $data["usertoken"]) {
            return $this->errorjson("usertoken错误");
        }
        $commentinfo = db("comments")->where("id", $data["id"])->find();
        if ($commentinfo == null) {
            return $this->errorjson("评论不存在");
        }
        $appinfo = db("appdown")->where("id", $commentinfo["appdownid"])->find();
        if ($appinfo == null) {
            return $this->errorjson("系统错误");
        }
        if ($userinfo["id"] != 1) {
            return $this->errorjson("不能删除其他人的评论哈");
        }
        db("comments")->where("id", $data["id"])->delete();
        return $this->successjson("删除成功");
    }

    //获取用户/软件评论
    public function listComment()
    {
        $data = input();
        $rule = [
            'userid|用户id' => 'number',
            'appid|软件id' => 'number',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if (!empty("appid") && !empty($data["userid"])) {
            return $this->errorjson("userid和appid必须传一个");
        }
        $where = "c.appdownid = {$data['appid']} ";
        if (!empty($data['userid'])) {
            $userinfo = db("user")->where("id", $data["userid"])->find();
            if ($userinfo == null) {
                return $this->errorjson("用户不存在");
            }
            $where .= " and c.userid = {$userinfo['id']}";
        }       
        
        if (!empty($data['appid'])) {
            $appinfo = db("appdown")->where("id", $data["appid"])->find();
            if ($appinfo == null) {
                return $this->errorjson("帖子不存在");
            }
            $where .= " and c.appdownid = {$appinfo['id']}";
        }
        $sort = input("?sort") ? $data["sort"] : "time";
        $sortOrder = input("?sortOrder") ? $data["sortOrder"] : 'desc';
        if ($sort != "time" && $sort != "id") {
            return $this->errorjson("sort参数错误");
        }
        if ($sortOrder != "desc" && $sortOrder != "asc") {
            return $this->errorjson("sortOrder参数错误");
        }
        $commentinfo = db('comments')
            ->alias("c")
            ->join("user u", "u.id = c.userid")
            ->join("appdown a", "a.id = c.appdownid")
            ->where($where)
            ->field("c.*,u.username,u.nickname,u.usertx")
            ->order("c." . $sort, $sortOrder)
            ->limit($this->limit)
            ->page($this->page)
            ->select();
        $commentcount = db("comments")
            ->alias("c")
            ->join("user u", "u.id = c.userid")
            ->join("appdown a", "a.id = c.appdownid")
            ->field("c.*")
            ->where($where)
            ->order("c.id", "desc")
            ->count();
        foreach ($commentinfo as $key => $value) {
            $commentinfo[$key]["usertx"] = $value["usertx"];
            //假入有上级评论则插入
            if ($value["parentid"] != 0) {
                $parentcommentinfo = db("comments")
                    ->alias("c")
                    ->join("user u", "u.id = c.userid")
                    ->join("appdown a", "a.id = c.appdownid")
                    ->where("c.id", $value["parentid"])
                    ->field("c.id,c.content,u.nickname,u.usertx")
                    ->find();
                if($parentcommentinfo){
                    $userinfo = db("user")->where("nickname", $parentcommentinfo["nickname"])->find();
                    //上级评论者用户ID
                    $commentinfo[$key]["parentuserid"] = $userinfo["id"];
                    //上级评论者用户昵称
                    $commentinfo[$key]["parentnickname"] = $parentcommentinfo["nickname"];
                    //上级评论者用户头像
                    $commentinfo[$key]["parenttx"] = $parentcommentinfo["usertx"];
                    //上级评论内容
                    $commentinfo[$key]["parentcontent"] = $parentcommentinfo["content"];
                }else{
                    $userinfo = db("user")->where("id", 1)->find();
                    //上级评论者用户ID
                    $commentinfo[$key]["parentuserid"] = 1;
                    //上级评论者用户昵称
                    $commentinfo[$key]["parentnickname"] = $userinfo["nickname"];
                    //上级评论者用户头像
                    $commentinfo[$key]["parenttx"] = $userinfo["usertx"];
                    $commentinfo[$key]["parentcontent"] = "该评论已删除";
                }
                
            }
        }
        $pagecount = ceil($commentcount / $this->limit);
        return $this->successjson($pagecount, $commentinfo);
    }

    //软件反馈
    public function sendmail()
    {
        $data = input();
        $rule = [
            'receiver|接收人邮箱' => 'require|email',
            'subject|邮件主题' => 'require',
            'content|邮件内容' => 'require',
            'setfrom|发件人名称' => 'require',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        $result = Mail::sendEmail($data["setfrom"], $data["receiver"], $data["subject"], $data["content"], 2);
        if ($result == 1) {
            return $this->successjson("ok");
        } else {
            return $this->errorjson($result);
        }
    }

    //软件置顶修改
    public function app_status()
    {
        $data = input();
        $rule = [
            'id|软件id' => 'require|number',
            'usertoken|用户token'=> 'require',
            'type|修改是否置顶' => 'require|number'
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if ($data["usertoken"]!='') {
            $userinfo = db("user")->where("usertoken", $data["usertoken"])->find();
        }
        if ($userinfo==null) {
            return $this->errorjson("usertoken错误");
        }
        if ($userinfo["id"]==1) {
            //置顶
            if ($data["type"] == 0) {
                $adddata = [
                    "apptop" => $data["type"],
                ];
                db("appdown")->where("id", $data["id"])->update($adddata);
                return $this->successjson("成功");
            }
            if ($data["type"] == 1) {
                $adddata = [
                    "apptop" => $data["type"],
                ];
                db("appdown")->where("id", $data["id"])->update($adddata);
                return $this->successjson("置顶成功");
            }
        } else {
            return $this->errorjson("权限不够");
        }
    }

    //获取广告列表
    public function getads()
    {
        $data = input();
        $result = db('appad')
            ->where('adtype',$data['type'])
            ->order('id', 'desc')
            ->select();
    
        return $this->successjson('获取成功', $result);
    }
}
